package com.bwie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.domain.GlobalStatusEnum;
import com.bwie.common.domain.User;
import com.bwie.common.domain.request.LoginUserRequest;
import com.bwie.common.domain.response.JwtResponse;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.exception.LoginException;
import com.bwie.remote.RemoteSysUserService;
import com.bwie.service.UserAuthService;
import com.bwie.sms.SendSmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author <a href="mailto:3364114353@qq.com">liuwenliang</a>
 * @version 1.0
 * @description:
 * @date 2025/9/9 10:05
 */
@Slf4j
@Service
public class UserAuthServiceImpl implements UserAuthService {

    @Autowired
    private RemoteSysUserService remoteSysUserService;

    @Autowired
    private SendSmsUtils sendSmsUtils;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public JwtResponse login(LoginUserRequest loginUserRequest) {
        //获取接收数据
        String phone = loginUserRequest.getPhone();
        String vercode = loginUserRequest.getVercode();
        //参数校验
        User loginUser = parameterVerification(phone);
        //获取缓存中的验证码
        String cache = (String) redisTemplate.opsForValue().get(phone);
        //判断验证码是否正确
        if (!StrUtil.equals(vercode, cache)) {
            throw new LoginException(GlobalStatusEnum.CODE_IS_ERROR.getLabel());
        }
        //将用户信息存储到缓存生成token
        JwtResponse jwtResponse = generateTokenAndStore(loginUser);
        return jwtResponse;
    }

    private JwtResponse generateTokenAndStore(User loginUser) {
        Map<String, Object> map = new HashMap<>();
        String userKey = IdUtil.fastSimpleUUID();
        //存储用户信息
        try {
            redisTemplate.opsForValue().set(userKey, loginUser, 30, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error("用户信息存储失败：{}", e.getMessage());
            throw new RuntimeException(e);
        }
        //生成token
        map.put(JwtConstants.USER_KEY, userKey);
        String token = JwtUtils.createToken(map);
        //组装，返回
        JwtResponse jwtResponse = new JwtResponse();
        jwtResponse.setToken(token);
        return jwtResponse;
    }

    @Override
    public void sendCode(String phone) {
        //参数校验
        User loginUser = parameterVerification(phone);
        //生成随机数，发送验证码
        String code = generateRandomAndStore(phone);
        //记录短信发送状态（远程调用）
        Result result = remoteSysUserService.addSmsRecord(loginUser);
        if (result.getCode() == GlobalStatusEnum.SYSTEM_IS_BUSY.getCode()) {
            throw new LoginException(GlobalStatusEnum.SYSTEM_IS_BUSY.getLabel());
        }
        //发送验证码
//        String key = "Try_Again";
//        SendSmsResponse sendSmsResponse = sendSmsUtils.sendSms(code, phone);
//        if (sendSmsResponse.getStatusCode() != 200) {
//            Long increment = redisTemplate.opsForValue().increment(key);
//            sendSmsUtils.sendSms(code, phone);
//            if (increment >= 3) {
//                throw new LoginException(GlobalStatusEnum.SEND_CODE_IS_FAILED.getLabel());
//            }
//        }
    }

    private String generateRandomAndStore(String phone) {
        //生成四位随机数
        double doubleRandom = Math.random() * (9999 - 1000 + 1) + 1000;
        Integer code = Integer.valueOf((int) doubleRandom);
        //将验证码存储到缓存
        try {
            redisTemplate.opsForValue().set(phone, String.valueOf(code), 5, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error("验证码存储失败：{}", e.getMessage());
            throw new RuntimeException(e);
        }
        return String.valueOf(code);
    }

    private User parameterVerification(String phone) {
        //非空校验
        if (StrUtil.isBlank(phone)) {
            throw new LoginException(GlobalStatusEnum.PHONE_IS_NULL.getLabel());
        }
        //判断手机号是否合法
        if (!phone.matches("^1[3-9][0-9]{9}$")) {
            throw new LoginException(GlobalStatusEnum.PHONE_IS_NOT_LEGITIMATE.getLabel());
        }
        //判断手机号是否存在（远程调用）
        Result<User> userResult = remoteSysUserService.selectPhoneIsExist(phone);
        if (userResult.getCode() == GlobalStatusEnum.SYSTEM_IS_BUSY.getCode()) {
            throw new LoginException(GlobalStatusEnum.SYSTEM_IS_BUSY.getLabel());
        }
        User loginUser = userResult.getData();
        if (ObjUtil.isNull(loginUser)) {
            throw new LoginException(GlobalStatusEnum.USER_IS_NOT_EXIST.getLabel());
        }
        return loginUser;
    }
}
